package com.googlecode.grima.servlet;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.googlecode.grima.domain.User;
import com.googlecode.grima.service.UserService;
import com.googlecode.grima.util.IOUtil;

public class AvatarServlet extends HttpServlet {

	/**
   * 
   */
  private static final long serialVersionUID = 3419242462329786828L;
	private UserService userService;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
	  super.init(config);
	  
	  WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
	  this.userService = (UserService) springContext.getBean("userService");
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String id = request.getParameter("id");
		if (id == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
			return;
		}

		InputStream is = getAvatarImage(id);
		if (is == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
			return;
		}

		OutputStream os;
		try {
			os = response.getOutputStream();
			IOUtil.copyStream(is, os);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public InputStream getAvatarImage(String id) {

		if ("".equals(id)){
			return null;
		}
		
		InputStream ret = null;
		Long longId = Long.valueOf(id);
		

		User user = userService.findById(longId);
		byte[] avatarImage = user.getAvatarImage();
		ret = new ByteArrayInputStream(avatarImage); 
		
		return ret;
	}

}